package com.phoenix.zhihu.filter;

import com.phoenix.zhihu.utils.CookieUtil;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@WebFilter(filterName = "myFilter",urlPatterns = "/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        System.out.println("过滤过滤！！！！！！！！！！");
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse)response;
        String url = request1.getRequestURI();
        if(url.contains(".css") || url.contains(".js") || url.contains(".png")||url.contains(".jpg")||url.contains("login")){
            chain.doFilter(request,response);
            return;
        }
        Cookie[] cookies = request1.getCookies();
        String username = "";
        username = CookieUtil.getValue(cookies,"zhihu");
        if(username==null||username.equals("")){
            response1.sendRedirect("/login.html");
            return;

        }else if(url.contains("admin")){
            chain.doFilter(request,response);
            return;

//            if (username.contains("admin")){
//                chain.doFilter(request,response);
//            }else {
//                response1.sendRedirect("/");
//
//            }
//            return;
        }
        chain.doFilter(request,response);


    }

    @Override
    public void destroy() {
    }
}
